import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'services/websocket_service.dart';
import 'controllers/keyboard_theme_controller.dart';
import 'pages/keyboard_page.dart';
import 'pages/empty_page.dart';
import 'pages/window_page.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Get.putAsync(() => WebSocketService().init());
  Get.put(KeyboardThemeController());
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Monitor',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.deepPurple,
          brightness: Brightness.light,
        ),
        useMaterial3: true,
      ),
      darkTheme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.deepPurple,
          brightness: Brightness.dark,
        ),
        useMaterial3: true,
      ),
      themeMode: ThemeMode.system,
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  int _selectedIndex = 0;
  bool _isExpanded = true;
  late AnimationController _animationController;
  late Animation<double> _animation;

  final List<NavigationDestination> _destinations = const [
    NavigationDestination(
      icon: Icon(Icons.keyboard),
      selectedIcon: Icon(Icons.keyboard, color: Colors.deepPurple),
      label: '键盘监控',
    ),
    NavigationDestination(
      icon: Icon(Icons.timeline),
      selectedIcon: Icon(Icons.timeline, color: Colors.deepPurple),
      label: '使用统计',
    ),
    NavigationDestination(
      icon: Icon(Icons.window),
      selectedIcon: Icon(Icons.window, color: Colors.deepPurple),
      label: '窗口记录',
    ),
    NavigationDestination(
      icon: Icon(Icons.network_check),
      selectedIcon: Icon(Icons.network_check, color: Colors.deepPurple),
      label: '网络监控',
    ),
    NavigationDestination(
      icon: Icon(Icons.memory),
      selectedIcon: Icon(Icons.memory, color: Colors.deepPurple),
      label: '系统状态',
    ),
  ];

  final List<Widget> _pages = [
    const KeyboardPage(),
    const EmptyPage(),
    const EmptyPage(),
    const EmptyPage(),
    const EmptyPage(),
  ];

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _animation = CurvedAnimation(
      parent: _animationController,
      curve: Curves.fastOutSlowIn,
    );
    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  void _toggleNavigation() {
    setState(() {
      _isExpanded = !_isExpanded;
      if (_isExpanded) {
        _animationController.forward();
      } else {
        _animationController.reverse();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final textTheme = Theme.of(context).textTheme;

    return Scaffold(
      body: Row(
        children: [
          NavigationRail(
            extended: _isExpanded,
            backgroundColor: colorScheme.surface,
            selectedIndex: _selectedIndex,
            onDestinationSelected: (int index) {
              setState(() {
                _selectedIndex = index;
              });
            },
            leading: Column(
              children: [
                const SizedBox(height: 8),
                IconButton(
                  icon: AnimatedIcon(
                    icon: AnimatedIcons.menu_arrow,
                    progress: _animation,
                  ),
                  onPressed: _toggleNavigation,
                ),
                if (_isExpanded) ...[
                  const SizedBox(height: 16),
                  SizedBox(
                    height: 50,
                    child: Row(
                      children: [
                        const SizedBox(width: 16),
                        Icon(
                          Icons.monitor,
                          size: 28,
                          color: colorScheme.primary,
                        ),
                        const SizedBox(width: 16),
                        Text(
                          'Monitor',
                          style: textTheme.titleLarge?.copyWith(
                            color: colorScheme.primary,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
                const SizedBox(height: 8),
                const Divider(),
              ],
            ),
            trailing: Expanded(
              child: Align(
                alignment: Alignment.bottomCenter,
                child: Padding(
                  padding: const EdgeInsets.only(bottom: 20),
                  child: IconButton(
                    icon: Icon(
                      Theme.of(context).brightness == Brightness.dark
                          ? Icons.light_mode
                          : Icons.dark_mode,
                    ),
                    onPressed: () {
                      Get.changeThemeMode(
                        Theme.of(context).brightness == Brightness.dark
                            ? ThemeMode.light
                            : ThemeMode.dark,
                      );
                    },
                  ),
                ),
              ),
            ),
            destinations: _destinations
                .map((d) => NavigationRailDestination(
                      icon: d.icon,
                      selectedIcon: d.selectedIcon,
                      label: Text(d.label),
                    ))
                .toList(),
          ),
          VerticalDivider(
            thickness: 1,
            width: 1,
            color: colorScheme.outlineVariant,
          ),
          Expanded(
            child: AnimatedSwitcher(
              duration: const Duration(milliseconds: 300),
              child: _pages[_selectedIndex],
            ),
          ),
        ],
      ),
    );
  }
}

class NavigationDestination {
  final Widget icon;
  final Widget selectedIcon;
  final String label;

  const NavigationDestination({
    required this.icon,
    required this.selectedIcon,
    required this.label,
  });
}
